<template>
  <div class="message-page">
    <Header />
    <div class="message-container">
      <!-- 原始提问 -->
      <el-card class="message-board-card">
        <div class="message-board-content">
          <div class="message-board-header">
            <div class="user-info">
              <span class="author">{{ messageBoard?.createrName }}</span>
              <span class="time">{{ messageBoard?.createTime }}</span>
            </div>
          </div>
          <div class="content-text">
            {{ messageBoard?.text }}
          </div>
        </div>
      </el-card>

      <!-- 回答列表 -->
      <div class="message-list">
        <h3 class="section-title">全部回答</h3>
        <el-card v-for="message in messages" 
          :key="message.messageId" 
          class="message-card"
        >
          <div class="message-content">
            <div class="message-header">
              <div class="user-info">
                <span class="author">{{ message.creatorName }}</span>
                <span class="user-type">{{ message.userType === 1 ? '医生' : '用户' }}</span>
                <span class="time">{{ message.createTime }}</span>
              </div>
            </div>
            <div class="content-text">
              {{ message.text }}
            </div>
          </div>
        </el-card>
      </div>

      <!-- 回答输入框 -->
      <div class="reply-section" v-if="isLoggedIn">
        <el-card class="reply-card">
          <div class="reply-header">
            <h3>我要回答</h3>
          </div>
          <el-form :model="messageForm" ref="messageFormRef" :rules="rules">
            <el-form-item prop="text">
              <el-input
                v-model="messageForm.text"
                type="textarea"
                :rows="4"
                placeholder="请输入您的回答..."
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitMessage">
                发表回答
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
      
      <!-- 未登录提示 -->
      <el-card v-else class="login-tip">
        <el-empty description="登录后即可回答">
          <el-button type="primary" @click="goToLogin">去登录</el-button>
        </el-empty>
      </el-card>
    </div>
    <Footer />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import Header from '../../components/header.vue'
import Footer from '../../components/footer.vue'
import { getMessageBoardDetail, type MessageBoard } from '../../api/messageboard'
import { getMessageList, createMessage, type Message } from '../../api/message'

const route = useRoute()
const router = useRouter()
const messageBoard = ref<MessageBoard>()
const messages = ref<Message[]>([])
const messageFormRef = ref()

const isLoggedIn = computed(() => {
  const userRole = localStorage.getItem('userRole')
  return !!userRole
})

const messageForm = ref({
  text: ''
})

const rules = {
  text: [
    { required: true, message: '请输入回答内容', trigger: 'blur' },
    { min: 10, max: 500, message: '内容长度应在10-500个字符之间', trigger: 'blur' }
  ]
}

// 获取提问详情
const fetchMessageBoardDetail = async () => {
  try {
    const res = await getMessageBoardDetail(Number(route.params.id))
    if (res.code === '200') {
      messageBoard.value = res.data.messageBoard
      console.log('设置提问详情:', messageBoard.value)
    } else {
      console.error('获取提问详情失败:', res.msg)
      ElMessage.error(res.msg || '获取提问详情失败')
    }
  } catch (error) {
    console.error('获取提问详情失败:', error)
    ElMessage.error('获取提问详情失败')
  }
}

// 获取回答列表
const fetchMessages = async () => {
  try {
    const res = await getMessageList(Number(route.params.id))
    if (res.code === '200') {
      messages.value = res.data
    }
  } catch (error) {
    console.error('获取回答列表失败:', error)
    ElMessage.error('获取回答列表失败')
  }
}

// 提交回答
const submitMessage = async () => {
  const userRole = localStorage.getItem('userRole')
  const userId = userRole === 'doctor' ? 
    localStorage.getItem('doctorid') : 
    localStorage.getItem('userid')
  const usertype = userRole === 'doctor' ? 1 : 0

  if (!userRole) {
    ElMessage.warning('请先登录后再回答')
    router.push('/login')
    return
  }

  if (!messageFormRef.value) return
  
  await messageFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const res = await createMessage({
          issueId: Number(route.params.id),
          creatorId: Number(userId),
          text: messageForm.value.text,
          usertype: usertype
        })
        if (res.code === '200') {
          ElMessage.success('回答成功')
          messageForm.value.text = ''
          fetchMessages()
        } else {
          ElMessage.error(res.msg || '回答失败')
        }
      } catch (error) {
        console.error('提交回答失败:', error)
        ElMessage.error('提交回答失败')
      }
    }
  })
}

// 跳转到登录页
const goToLogin = () => {
  // 保存当前路径用于登录后重定向
  localStorage.setItem('redirectPath', route.fullPath)
  router.push('/login')
}

onMounted(() => {
  fetchMessageBoardDetail()
  fetchMessages()
})
</script>

<style scoped>
.message-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.message-container {
  width: 800px;
  margin: 40px auto;
  padding: 0 20px;
  flex: 1;
}

.message-board-card {
  margin-bottom: 30px;
}

.message-board-content {
  padding: 20px;
}

.message-board-header {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.section-title {
  margin: 30px 0 20px;
  color: #2c3e50;
  font-size: 18px;
  font-weight: 500;
}

.message-card {
  margin-bottom: 20px;
}

.message-content {
  padding: 20px;
}

.message-header {
  margin-bottom: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author {
  color: #409EFF;
  font-weight: 500;
}

.user-type {
  background-color: #67c23a;
  color: white;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}

.time {
  color: #909399;
  font-size: 14px;
}

.content-text {
  color: #606266;
  font-size: 16px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

.reply-section {
  margin-top: 40px;
}

.reply-header {
  margin-bottom: 20px;
}

.reply-header h3 {
  color: #2c3e50;
  font-size: 18px;
  margin: 0;
}

.login-tip {
  margin-top: 40px;
  text-align: center;
  padding: 40px;
}
</style>
